<!--
 * @Description: 业务管理系统
 * @Author: fxg
 * @Date: 2020-06-29 11:18:28
 * @LastEditors: wangwangwang
 * @LastEditTime: 2021-04-14 16:37:58
-->
<template>
  <div class="pages_content taskyTypes table">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main>
        <div class="header_right" @click="showCardNav = !showCardNav">
          <div class="title">搜索</div>
          <div>
            <transition name="from"></transition>
            <span v-show="!showCardNav"><i style="margin-right: 5px;" class="el-icon-arrow-down"></i></span>
            <transition name="to"></transition>
            <span v-show="showCardNav"><i style="margin-right: 5px;" class="el-icon-arrow-up"></i></span>
          </div>
        </div>
        <div v-show="showCardNav" class="hr"></div>
        <el-collapse-transition>
          <div v-show="showCardNav">
            <div class="search">
              <span style="display: inline-block;margin-bottom: 10px;">
                <span style="margin-right: 12px;">委托人</span>
                <el-input v-model="tableParam.entrustUserName" style="width: 200px;" clearable placeholder="请输入"  @keyup.enter.native="queryPage()"/>
              </span>
              <span style="margin-left: 36px;">
                <span style="margin-right: 12px;">开始时间</span>
                <el-date-picker v-model="tableParam.startTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请选择"></el-date-picker>
              </span>
              <span style="margin-left: 36px;">
                <span style="margin-right: 12px;">结束时间：</span>
                <el-date-picker v-model="tableParam.endTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请选择"></el-date-picker>
              </span>
              <el-button icon="el-icon-search" size="medium" class="bottom_all" @click="(tableParam.page = 1), queryPage()">查 询</el-button>
              <el-button size="medium" class="bottom_all_two" @click="reset()">重 置</el-button>
            </div>
          </div>
        </el-collapse-transition>
        <div class="hr"></div>
        <div class="card">
          <div class="card_nav">
            <div>
              <el-button size="small" class="bottom_all" style="margin-left: 0;" @click="add()">
                <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
                添加
              </el-button>
              <el-button size="small" class="bottom_two" @click="batchUpdateOrDelete('update_status', 0)">
                <i class="icon iconfont iconicon_button_delete" style="font-size: 12px;"></i>
                删除
              </el-button>
              <el-button size="small" class="bottom_three" @click="batchUpdateOrDelete('update_enable', 1)">
                <i class="icon iconfont iconicon_button_startuse" style="font-size: 12px;"></i>
                启用
              </el-button>
              <el-button size="small" class="bottom_four" @click="batchUpdateOrDelete('update_enable', 0)">
                <i class="icon iconfont  iconicon_button_disable1" style="font-size: 12px;"></i>
                禁用
              </el-button>
            </div>
            <div>
              <el-link :underline="false" @click="updateSortNum()">
                <span class="el-icon--left"><i class="iconfont iconicon_button_sort1"></i></span>
                保存排序号
              </el-link>
              <el-dropdown :hide-on-click="false" trigger="click" style="margin: 0 20px;">
                <el-link :underline="false">
                  <span class="el-icon--left"><i class="iconfont iconicon_button_filtrate"></i></span>
                  筛选
                </el-link>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-for="(item, index) in table" :key="index">
                    <el-checkbox v-model="item.status">{{ item.label }}</el-checkbox>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-link :underline="false" @click="$Download(DownloadURL, tableParam)">
                <span class="el-icon--left"><i class="iconfont iconicon_button_export1"></i></span>
                导出
              </el-link>
            </div>
          </div>
          <div class="card_info" :style="style">
            <el-table ref="multipleTable" :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="tableData" tooltip-effect="dark" @selection-change="handleSelectionChange">
              <el-table-column align="center" type="selection" width="50"></el-table-column>
              <template v-for="(item, index) in table">
                <el-table-column v-if="item.status" :key="index" :label="item.label" align="center" :width="item.width" :fixed="item.label =='操作'?'right':false">
                  <template slot-scope="scope">
                    <el-button v-if="item.label == '操作'" class="bottom_one" size="mini" @click="update(scope.row)">
                      <i class="icon iconfont iconicon_button_modification" style="font-size: 12px;"></i>
                      修改
                    </el-button>
                    <span v-if="item.label == '代理类型'">{{ proxyType | fromatTable(scope.row.proxyType, 'name', 'id') }}</span>
                    <span v-if="item.label == '代理方式'">{{ proxyWay | fromatTable(scope.row.proxyWay, 'name', 'id') }}</span>
                    <div v-if="item.label == '流程'">
                      <el-button v-if="scope.row.proxyWay==2" type="text" size="mini" @click="show(scope.row)">
                        查看流程
                      </el-button>
                    </div>

                    <span v-if="scope.row.enable == 0 && item.label == '状态'" style="color:#969799;">禁用</span>
                    <span v-if="scope.row.enable == 1 && item.label == '状态'" style="color:#00A754;">启用</span>
                    <!-- <span v-if="item.label == '状态'">{{ dataSourcearr | fromatTable(scope.row.dataSource, 'name', 'id') }}</span> -->
                    <span v-if="item.label !== '操作' && item.label !== '代理类型' && item.label !== '代理方式'&& item.label !== '状态'">{{ scope.row[item.prop] }}</span>
                  </template>
                </el-table-column>
              </template>
            </el-table>
          </div>
        </div>
      </el-main>
      <div class="card_bottom">
        <div class="card_bottom_left">
          <div class="top_page_totle">总共{{ total }}条</div>
          <el-pagination :current-page.sync="tableParam.page" :page-size="tableParam.pageSize" :page-sizes="[10, 20, 30, 40,50,100,200,500,1000]" layout="prev,pager,sizes,next,jumper" :total="total" @size-change="sizeChange" @current-change="queryPage()"></el-pagination>
        </div>
        <div>
          <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="queryPage()">刷新</el-button>
        </div>
      </div>
    </el-container>
    <!-- 添加 -->
    <el-dialog v-dialogDrag :visible.sync="dialogVisible" width="880px" :close-on-click-modal="false" :before-close="resefrom">
      <span slot="title" class="dialog-title">{{ dialogtitle }}</span>
      <div class="dialoginfo">
        <el-form ref="reffromDate" :rules="rules" :inline="true" :model="from" label-width="110px">
          <el-form-item prop="entrustUserId">
            <span slot="label" style="color: #ff0000">委托人：</span>
            <!-- <el-select v-model="from.entrustUserId" filterable placeholder="请选择">
              <el-option v-for="item in userarr" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select> -->
            <span style="cursor: pointer;" @click="choisePerson(1)">{{from.entrustUserName}}</span>
          </el-form-item>
          <el-form-item prop="proxyUserId">
            <span slot="label" style="color: #ff0000">代理人：</span>
            <!-- <el-select v-model="from.proxyUserId" filterable placeholder="请选择">
              <el-option v-for="item in userarr" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select> -->
            <span style="cursor: pointer;" @click="choisePerson(2)">{{from.proxyUserName}}</span>
          </el-form-item>
          <el-form-item prop="startTime">
            <span slot="label" style="color: #ff0000">开始时间：</span>
            <el-date-picker v-model="from.startTime" style="width:215px" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期时间"></el-date-picker>
          </el-form-item>
          <el-form-item prop="endTime">
            <span slot="label" style="color: #ff0000">结束时间：</span>
            <el-date-picker v-model="from.endTime" style="width:215px" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期时间"></el-date-picker>
          </el-form-item>
          <el-form-item prop="enable">
            <span slot="label">状态：</span>
            <el-radio-group v-model="from.enable">
              <el-radio v-for="(item,index) in enable" :key="index" :label="item.id">{{item.name}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <div>
            <el-form-item prop="proxyType">
              <span slot="label">代理类型：</span>
              <el-checkbox-group v-model="from.proxyType">
                <el-checkbox v-for="(item,index) in proxyType" :key="index" :label="item.id">{{item.name}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </div>
          <el-form-item prop="proxyType">
            <span slot="label">代理方式：</span>
            <el-radio-group v-model="from.proxyWay">
              <el-radio v-for="(item,index) in proxyWay" :key="index" :label="item.id">{{item.name}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div v-show="from.proxyWay==2">
          <el-input v-model="searchValue" style="width: 200px;" clearable placeholder="请输入" />
          <el-button class="bottom_all" @click="searchSubmit()">确 定</el-button>
        </div>
        <div v-show="from.proxyWay==2" style="height:400px" class="scroll">
          <el-tree ref="treeNode" node-key="id" class="tree-line" check-on-click-node :indent="0" highlight-current show-checkbox :data="showTreeArry" :check-strictly="true" :props="defaultProps"></el-tree>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resefrom()">取 消</el-button>
        <el-button class="bottom_all" @click="save()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 查看流程 -->
    <el-dialog v-dialogDrag :visible.sync="traaDateshow" width="300px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">查看流程</span>
      <div class="traaDate-info scroll">
        <el-tree :key="time" node-key="id" class="tree-line" :indent="0" :expand-on-click-node="false" :data="treeArry" :props="defaultProps">
          <span slot-scope="{ node ,data}" class="custom-tree-node">
            <span :style="oldproxyProcessList.some(res=>(res==data.id))?'color:'+bgcolor:''">{{ node.label }}</span>
          </span>
        </el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" size="medium" @click="traaDateshow=false">关 闭</el-button>
      </span>
    </el-dialog>
    <personModel :visible='visible' :isPerson="true" @closeModel='closeModel' @getPerson='getPerson' />
  </div>
</template>

<script>
import breaDcrumb from '@/components/breadcrumb';
import personModel from '@/components/ChoisePerson/personModel';
import { mapGetters } from 'vuex';
import { queryPage, saveOrUpdate, updateSortNum, Download, batchUpdateOrDelete, get_detail } from '@/api/Signed/processAgent.js';
import { queryPage as businessqueryPage } from '@/api/basedata/business';
import { getFlowsList } from '@/api/Signed/flows';
import { formatTreeData } from '@/utils/utils'
import styles from "@/app.scss";
export default {
  components: {
    breaDcrumb,
    personModel,
  },
  data() {
    return {
      DownloadURL: Download,
      /*判断收起展开*/
      dialogVisible: false,
      visible: false,
      searchValue: '',
      dialogtitle: '添加',
      showCardNav: true,
      /*搜索关键字段*/
      /*列表展示*/
      enable: [{ name: '禁用', id: 0 }, { name: '启用', id: 1 }],
      proxyWay: [{ name: '全部', id: 1 }, { name: '自定义流程', id: 2 }],
      proxyType: [{ name: '代理创建流程', id: 1 }, { name: '代理审批流程', id: 2 }, { name: '代理已办流程', id: 3 }],
      table: [
        { label: '委托人', width: 'auto', prop: 'entrustUserName', status: true },
        { label: '代理人', width: 'auto', prop: 'proxyUserName', status: true },
        { label: '开始时间', width: '140', prop: 'startTime', status: true },
        { label: '结束时间', width: '140', prop: 'endTime', status: true },
        { label: '代理类型', width: 'auto', prop: 'proxyWay', status: true },
        { label: '代理方式', width: '120', prop: 'proxyType', status: true },
        { label: '流程', width: '120', prop: '', status: true },
        { label: '状态', width: 'auto', prop: 'enable', status: true },
        { label: '创建人', width: '120', prop: 'createUserName', status: true },
        { label: '创建时间', width: '140', prop: 'createTime', status: true },
        { label: '修改人', width: '120', prop: 'updateUserName', status: true },
        { label: '修改时间', width: '140', prop: 'updateTime', status: true },
        { label: '操作', width: '120', prop: '', status: true }
      ],
      rules: {
        entrustUserId: [{ required: true, message: "请选择委托人", trigger: "change" }],
        proxyUserId: [{ required: true, message: "请选择代理人", trigger: "change" }],
        startTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
        endTime: [{ required: true, message: "请选择结束时间", trigger: "change" }],
      },
      from: {
        entrustUserName: '请选择',
        entrustUserId: '',
        proxyUserName: '请选择',
        proxyUserId: '',
        startTime: '',
        endTime: '',
        enable: 1,
        proxyType: [],
        proxyWay: 1,
        proxyProcessList: []
      },
      /*列表选中的数据集*/
      tableParam: {
        page: 1,
        pageSize: 10,
        entrustUserName: '',
        startTime: '',
        endTime: ''
      },
      ids: [],
      sortIds: [],
      total: 0,
      tableData: [],
      treeArry: [],
      defaultProps: {
        children: "children",
        label: "name"
      },
      oldproxyProcessList: [],
      traaDateshow: false,
      time: '',
      bgcolor: styles.bg_color,
      personType: '',
      allFlows: [],
      showTreeArry: [],
    };
  },
  mounted() {
    let params = {
      page: 1,
      pageSize: 10000000,
      userEentrance: 'entrance_manager',
    };
    /**获取所有流程*/
    businessqueryPage(params).then(res => {
      let systemList = res.data.data.map((item) => (
        { ...item, parentId: 0 }
      ));
      getFlowsList(params).then(res => {
        if (res.code === 1001) {
          const newData = res.data.data.map((item) => (
            item.parentId === 'parent_id' ? { ...item, parentId: item.systemId } : { ...item }
          ))
          this.allFlows = res.data.data;
          this.treeArry = formatTreeData(newData.concat(systemList), 'id', 'parentId', 'children', 0);
          this.showTreeArry = this.treeArry;
        }
      });
    })
    this.queryPage();
  },
  methods: {
    searchSubmit() {
      if (this.searchValue) {
        const newData = this.allFlows.filter(item => item.name.indexOf(this.searchValue) > -1);
        this.showTreeArry = newData;
        return
      }
      this.showTreeArry = this.treeArry;
    },
    getPerson(data) {
      if (this.personType === 1) {
        this.from.entrustUserName = data[0].name;
        this.from.entrustUserId = data[0].id;
      } else {
        this.from.proxyUserName = data[0].name;
        this.from.proxyUserId = data[0].id;
      }
      console.log(this.from)
      this.visible = false;
    },
    closeModel() {
      this.visible = false;
    },
    choisePerson(type) {
      this.personType = type;
      this.visible = true;
    },
    show(low) {
      let _this = this
      _this.traaDateshow = true
      get_detail({ proxyManagerId: low.id }).then(res => {
        _this.oldproxyProcessList = res.data.proxyProcessList.map(res => (res.processManagerId))
        console.log(_this.oldproxyProcessList)
        _this.time = new Date().getTime()
      })
    },
    save() {
      let _this = this;
      _this.$refs.reffromDate.validate((valid) => {
        if (valid) {
          let fromDate = JSON.parse(JSON.stringify(_this.from))
          fromDate.proxyType = fromDate.proxyType.join(',')
          if (fromDate.proxyWay == 2) {
            let arr = _this.$refs.treeNode.getCheckedNodes(true);
            let allHasData = arr.filter((item) => (
              this.oldproxyProcessList.some((items) => (item.id == items.processManagerId))
            ))
            let delData = this.oldproxyProcessList.filter((item) => (
              !allHasData.some((items) => (item == items.id))
            ))
            let addData = arr.filter((item) => (
              !allHasData.some((items) => (item.id == items.id))
            ))
            addData = addData.map(res => ({ processManagerId: res.id, processManagerName: res.name }))
            delData = delData.map(res => ({
              processManagerId: res.processManagerId,
              proxyManagerId: res.proxyManagerId,
              processManagerName: res.processManagerName,
              id: res.id,
              status: 0
            }))
            fromDate.proxyProcessList = [...addData, ...delData]
          }
          if (fromDate.proxyWay == 1) {
            fromDate.proxyProcessList = this.oldproxyProcessList.map(res => ({
              processManagerId: res.processManagerId,
              proxyManagerId: res.proxyManagerId,
              id: res.id,
              status: 0
            }))
          }
          saveOrUpdate(fromDate).then((res) => {
            if (res.code == 1001) {
              _this.$message({
                message: '保存成功',
                type: 'success'
              });
              _this.queryPage();
              _this.resefrom();
            }
          });
        } else {
          return false;
        }
      });

    },
    /*获取数据*/
    queryPage() {
      queryPage(this.tableParam).then(res => {
        this.total = res.data.totalRows;
        this.tableData = res.data.data;
      });
    },
    /*重置*/
    reset() {
      this.tableParam.entrustUserName = '';
      this.tableParam.startTime = '';
      this.tableParam.endTime = '';
      this.queryPage();
    },
    resefrom() {
      this.dialogVisible = false;
      this.from = {
        entrustUserId: '',
        proxyUserId: '',
        startTime: '',
        endTime: '',
        enable: 1,
        proxyType: [],
        proxyWay: 1,
        proxyProcessList: []
      };
    },
    updateSortNum() {
      updateSortNum(this.sortIds).then(() => {
        this.queryPage();
      });
    },
    add() {
      this.dialogtitle = '添加';
      this.dialogVisible = true;
      setTimeout(() => {
        this.$refs.reffromDate.clearValidate();
      }, 10);
      this.from.entrustUserName = '请选择';
      this.from.proxyUserName = '请选择';
    },
    update(data) {
      let _this = this
      let str = JSON.stringify(data);
      _this.from = JSON.parse(str);
      _this.from.proxyType = this.from.proxyType.split(',').map(Number)
      _this.dialogtitle = '修改';
      get_detail({ proxyManagerId: _this.from.id }).then(res => {
        let arr = res.data.proxyProcessList.map(res => (res.processManagerId))
        this.oldproxyProcessList = res.data.proxyProcessList
        if (_this.from.proxyWay == 2) {
          _this.$refs.treeNode.setCheckedKeys(arr)
        }
      })
      _this.dialogVisible = true;
      str = null;
    },
    /*删除*/
    batchUpdateOrDelete(type, status) {
      if (this.ids.length == 0) {
        this.$message({
          message: '请选择要操作的数据项',
          type: 'warning'
        });
        return;
      }
      if (type === 'update_status') {
        this.$confirm('此操作将永久删除该信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'bottom_all_two',
          confirmButtonClass: 'bottom_all',
          type: 'warning'
        })
          .then(() => {
            batchUpdateOrDelete({
              ids: this.ids,
              status: status,
              type: type
            }).then(() => {
              this.reset();
            });
          })
          .catch(() => { });
      } else {
        batchUpdateOrDelete({
          ids: this.ids,
          status: status,
          type: type
        }).then(() => {
          this.queryPage();
        });
      }
    },
    /*批量选择*/
    handleSelectionChange(val) {
      this.ids = [];
      this.sortIds = [];
      val.forEach(item => {
        this.ids.push(item.id);
        this.sortIds.push({ id: item.id, sortNum: item.sortNum });
      });
    },
    sizeChange(value) {
      this.tableParam.pageSize = value;
      this.queryPage();
    },
  },
  computed: {
    ...mapGetters({
      screenWidth: 'getscreenWidth',
      screenHeight: 'getscreenHeight',
      Collapse: 'getsCollapse'
    }),
    style() {
      let num = 0;
      if (this.Collapse) {
        num = this.screenWidth - 124;
      } else {
        num = this.screenWidth - 220;
      }
      return 'width:' + num + 'px;';
    }
  }
};
</script>
<style lang="scss" scoped>
.traaDate-info {
  min-height: 400px;
  max-height: 600px;
  overflow: auto;
}
.taskyTypes {
  .el-link {
    i {
      font-size: 14px;
      color: $bg_color;
    }
  }
  .el-link:hover {
    color: $bg_color;
  }
  font-size: $font_size;
}
</style>
